package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.DrawActivityRepository;
import cn.com.connext.scrm.repository.master.PrizeGoodRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.utils.ErpUtils;
import cn.com.connext.scrm.web.rest.vm.ActivityProbabilityVM;
import cn.com.connext.scrm.web.rest.vm.DrawActivityVM;
import cn.com.connext.scrm.web.rest.vm.PrizeGoodVM;
import cn.com.connext.scrm.web.rest.vm.QueryPrizeVM;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 2 * @Author: shawn
 * 3 * @Date: 2020/8/11 4:16 下午
 * 4
 */
@Service
@Transactional
public class PrizeGoodService {

    private final Logger log = LoggerFactory.getLogger(PrizeGoodService.class);

    @Autowired
    private PrizeGoodRepository prizeGoodRepository;
    @Autowired
    private DrawActivityRepository drawActivityRepository;
//    @Autowired
//    private ErpLogisticsService erpLogisticsService;

    public void edit(PrizeGoodVM vm) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PrizeGood good;
        if (vm.getId() != null) {
            good = prizeGoodRepository.findOne(vm.getId());
        } else {
            good = new PrizeGood();
            good.setEnable(false);
        }
        good.setActivityId(vm.getActivityId());
        if (StringUtils.isNotEmpty(vm.getGoodName())) {
            good.setGoodName(vm.getGoodName());
        }
        if (StringUtils.isNotEmpty(vm.getGoodImg())) {
            good.setGoodImg(vm.getGoodImg());
        }
        if (vm.getStock() != null &&vm.getStock()>=0) {
            good.setStock(vm.getStock());
        }
        if (vm.getType() != null) {
            good.setType(vm.getType());
        }
        if (vm.getProbability() != null) {
            good.setProbability(vm.getProbability());
        }
        if (vm.getIsCheck() != null) {
            good.setIsCheck(vm.getIsCheck());
        }
        if (StringUtils.isNotEmpty(vm.getCouponType())) {
            good.setCouponType(vm.getCouponType());
        }
        if(StringUtils.isNotEmpty(vm.getBottomImg())){
            good.setBottomImg(vm.getBottomImg());
        }
        if(StringUtils.isNotEmpty(vm.getSpecNo())){
            good.setSpecNo(vm.getSpecNo());
        }
        if(StringUtils.isNotEmpty(vm.getGoodsNo())){
            good.setGoodsNo(vm.getGoodsNo());
        }
        if(StringUtils.isNotEmpty(vm.getBottomImg())){
            good.setBottomImg(vm.getBottomImg());
        }

        // 2021-4-20 新增礼品CODE和奖品兑换开始时间字段
        if(StringUtils.isNotBlank(vm.getGoodCode())){
            good.setGoodCode(vm.getGoodCode());
        }
        if (StringUtils.isNotEmpty(vm.getExpireStartDate())) {
            try {
                log.info("getExpireStartDate:{}", vm.getExpireStartDate());
                good.setExpireStartDate(sdf.parse(vm.getExpireStartDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        good.setPagePath(vm.getPagePath());
        if (StringUtils.isNotEmpty(vm.getExpireDate())) {
            try {
                log.info("startTime:{}", vm.getExpireDate());
                good.setExpireDate(sdf.parse(vm.getExpireDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        if (StringUtils.isNotEmpty(vm.getExpireDate())) {
            try {
                log.info("startTime:{}", vm.getExpireCallDate());
                good.setExpireCallDate(sdf.parse(vm.getExpireCallDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        if (vm.getPoint() != null) {
            good.setPoint(vm.getPoint());
        }
        if (StringUtils.isNotEmpty(vm.getCardId())) {
            good.setCardId(vm.getCardId());
        }
        if (StringUtils.isNotEmpty(vm.getCode())) {
            good.setCode(vm.getCode());
        }
        if (StringUtils.isNotEmpty(vm.getRemark())){
            good.setRemark(vm.getRemark());
        }
        if (StringUtils.isNotEmpty(vm.getCouponType())){
            good.setCouponType(vm.getCouponType());
        }
        if (StringUtils.isNotEmpty(vm.getCouponType())){
            good.setCouponType(vm.getCouponType());
        }
        if (StringUtils.isNotEmpty(vm.getStartTime())) {
            try {
                log.info("startTime:{}", vm.getStartTime());
                good.setStartTime(sdf.parse(vm.getStartTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(vm.getEndTime())) {
            try {
                log.info("endTime:{}", vm.getEndTime());
                good.setEndTime(sdf.parse(vm.getEndTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        good.setButtonText(vm.getButtonText());
        if (vm.getPathType()!=null){
            good.setPathType(vm.getPathType());
        }
        if (StringUtils.isNotEmpty(vm.getAppId())){
            good.setAppId(vm.getAppId());
        }
        if (vm.getIsbig()!=null){
            good.setIsbig(vm.getIsbig());
        }
        if (vm.getBigcount()!=null){
            good.setBigcount(vm.getBigcount());
        }
        if (vm.getMonth()!=null){
            good.setMonth(vm.getMonth());
        }
        good.setMgmStatus(vm.getMgmStatus());
        good.setMgmButtonName(vm.getMgmButtonName());
        good.setMgmUrl(vm.getMgmUrl());
        good.setQrCodeId(vm.getQrCodeId());
        good.setHxContent1(vm.getHxContent1());
        good.setHxContent2(vm.getHxContent2());
        if (StringUtils.isNotEmpty(vm.getCouponNature())) {
            good.setCouponNature(vm.getCouponNature());
        }
        //210804 新增微信代金券
        if (StringUtils.isNotEmpty(vm.getWxCouponsType())) {
            good.setWxCouponsType(vm.getWxCouponsType());
        }
        if (StringUtils.isNotEmpty(vm.getStockId())) {
            good.setStockId(vm.getStockId());
        }
        if (StringUtils.isNotEmpty(vm.getStockCreatorMchid())) {
            good.setStockCreatorMchid(vm.getStockCreatorMchid());
        }
        prizeGoodRepository.saveAndFlush(good);
    }

    public Page<PrizeGood> list(QueryPrizeVM vm) {
        Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize(),Sort.Direction.DESC, "id");
        Specification<PrizeGood> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(vm.getActivityId())) {
                list.add(criteriaBuilder.equal(root.get("activityId"), vm.getActivityId()));//活动ID
            }
            if (StringUtils.isNotEmpty(vm.getPrizeGoodName())) {
                list.add(criteriaBuilder.equal(root.get("goodName"), vm.getPrizeGoodName()));//问答
            }
            if (null != vm.getType()) {
                list.add(criteriaBuilder.equal(root.get("type"), vm.getType()));
            }
            if (null != vm.getEnable()) {
                list.add(criteriaBuilder.equal(root.get("isEnable"), vm.getEnable()));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<PrizeGood> page = prizeGoodRepository.findAll(specification, pageable);
        return page ;
    }


    public PrizeGood detail(Integer id) {
        PrizeGood good = prizeGoodRepository.findOne(id);
        return good;
    }

    public void delete(Integer id) {
        prizeGoodRepository.delete(id);
    }

    public void enable(Integer id) {
        PrizeGood good = prizeGoodRepository.findOne(id);
        if (good.getEnable()) {
            good.setEnable(false);
        } else {
            good.setEnable(true);
        }
        prizeGoodRepository.saveAndFlush(good);
    }

    public List<PrizeGood> getEnableIdsAndStockIsNotNull() {
        List<PrizeGood> ids = prizeGoodRepository.getEnableIdsAndStockIsNotNull();
        return ids;
    }

    public List<PrizeGood> getEnableIdsAndStockIsNotNullByActivityId(String activityId) {
        List<PrizeGood> ids = prizeGoodRepository.getEnableIdsAndStockIsNotNullByActivityId(activityId);
        return ids;
    }

    public Boolean cutStock(Integer goodId, String activityId) {
        //获取抽中的奖品扣库存
        PrizeGood goods = prizeGoodRepository.findByIdAndActivityId(goodId, activityId);
        if (goods.getStock() > 0) {
            goods.setStock(goods.getStock() - 1);
            PrizeGood result = prizeGoodRepository.saveAndFlush(goods);
            log.info("result:{}", JSON.toJSONString(result));
            return true;
        }
        return false;
    }

    public String getName(Integer goodId) {
        PrizeGood one = prizeGoodRepository.findOne(goodId);
        String name = "";
        if (one != null) {
            name = prizeGoodRepository.findOne(goodId).getGoodName();
        }
        return name;
    }


    public PrizeGood findById(Integer goodId) {
        PrizeGood prizeGood = prizeGoodRepository.findOne(goodId);
        return prizeGood;
    }

    public PrizeGood findByActivityIdAndType(String activityId, Integer type) {
        List<PrizeGood> prizeGood = prizeGoodRepository.findAllByActivityIdAndType(type, activityId);
        if (prizeGood.size() > 0)
            return prizeGood.get(0);
        else
            return null;
    }

    public List<PrizeGood> findByActivityId(String activityId){
        return prizeGoodRepository.findByActivityId(activityId);
    }

    public List<PrizeGood> findDwaByActivityId(String activityId) {
        return prizeGoodRepository.findDwaByActivityId(activityId);
    }

    public List<PrizeGood> findExpiredDwaByActivityId(String activityId, List<Integer> goodIds) {
        return prizeGoodRepository.findExpiredDwaByActivityId(activityId,goodIds);
    }

    public List<PrizeGood> findDwaByActivityIdAndGoodIds(String activityId, List<Integer> goodIds) {
        return prizeGoodRepository.findDwaByActivityIdAndGoodIds(activityId,goodIds);
    }

    public PrizeGood findCanUse(Integer goodId) {
        return prizeGoodRepository.findCanUse(goodId);
    }

    public void updatePrizeGood(PrizeGood pd) {
        prizeGoodRepository.saveAndFlush(pd);
    }

    public String getActivityName(String activityId) {
        DrawActivity one = drawActivityRepository.findOne(activityId);
        String activityName = "";
        if (one != null) {
            activityName = one.getActivityName();
        }
        return activityName;
    }

    public JsonResult findAllMdmGood(DrawActivityVM req) {
        JsonResult result =new JsonResult();
        if(req ==null || StringUtils.isEmpty(req.getId())){
            result.setMessage("用户参数不能为空!");
            result.setState(-1);
        }else{
            List<PrizeGood> list = prizeGoodRepository.findDwaByActivityId(req.getId());
            result.setMessage("数据如下");
            result.setData(list);
            result.setState(0);
        }
        return result;
    }

    public void LogisticsSyncQuery() {
        JsonResult result = ErpUtils.LogisticsSyncQuery();
//        if(result.getState() ==0){
//            List<ErpLogistics> list  =(List<ErpLogistics>)result.getData();
//            if(list !=null && list.size() >0){
//                erpLogisticsService.save(list);
//                log.info("本次同步物流订单信息"+list.size()+"条");
//            }
//        }else{
//            log.info("第三方接口异常，异常信息"+result.toString());
//        }
    }

    public List<PrizeGood> findByIds(List<Integer> goodIds,List<Integer> typeList) {
        return prizeGoodRepository.findByIds(goodIds,typeList);
    }

    public List<PrizeGood> getEnableIdsByActivityId(String activityId) {
        List<PrizeGood> ids = prizeGoodRepository.getEnableIdsByActivityId(activityId);
        return ids;
    }

    /**
     * 查询活动下奖品总概率
     * */
    public JsonResult queryActivityProbability(ActivityProbabilityVM vm) {
        JsonResult result =new JsonResult();
        try {
            Double probabilityCount = 0D;
            probabilityCount = vm.getProbability();
            //goodId不为空则是修改，修改时查询去除自身数据库中概率再进行计算
            if (vm.getGoodId() != null) {
                Double probability = prizeGoodRepository.findProbabilityByActivityIdAndId(vm.getActivityId(), vm.getGoodId());
                if (probability != null) {
                    probabilityCount = probabilityCount + probability;
                }
            } else {
                Double probability = prizeGoodRepository.findProbabilityByActivityId(vm.getActivityId());
                if (probability != null) {
                    probabilityCount = probabilityCount + probability;
                }
            }
            result.setData(probabilityCount);
            result.setState(0);
        }catch (Exception e){
            log.error("PrizeGoodService.queryActivityProbability error:{}", e);
            result.setMessage("系统繁忙");
            result.setState(-1);
        }
        return result;
    }

    /**
     * 查询礼品CODE是否存在
     * @param goodCode
     * @return
     */
    public List<PrizeGood> findByGoodCode(String goodCode){
        return prizeGoodRepository.findByGoodCode(goodCode);
    }

    /**
     * 编辑奖品查询奖品CODE是否存在
     * @param goodCode
     * @return
     */
    public List<PrizeGood> findByGoodCodeAndId(String goodCode,  Integer id){
        return prizeGoodRepository.findByGoodCodeAndId(goodCode, id);
    }
}
